import React, {Component} from "react";
import {Text, requireNativeComponent} from "react-native";

const PropTypes = require('prop-types');

const AndroidListView = requireNativeComponent('RCTListView', null);
const AndroidFrameLayout = requireNativeComponent('RCTFrameLayout', null);
const ColorPropType = require('ColorPropType');
/**
 * 还有一个bug没解决(滑动过快时会出现)
 */
export default class ListView extends Component {
    static defaultProps = {
        data: [],
        emptyView:(<Text style={{textAlignVertical:"center",textAlign:"center",fontSize:20}}> 没有内容!</Text>),
        renderItem: (viewKey, item) => {
        },
        maxRows: 30,
        isPadding: [false, false, false, false]
    };
    static propTypes = {
        data: PropTypes.array.isRequired,
        renderItem: PropTypes.func.isRequired,
        maxRows: PropTypes.number,
        dividerHeight: PropTypes.number,
        dividerColor: ColorPropType,
        isPadding: PropTypes.arrayOf(PropTypes.bool),
    };

    constructor(props) {
        super(props);
        this.state = {
            views: []
        }
    }

    render() {
        return (
            <AndroidFrameLayout>
                {this.props.emptyView}
                <AndroidListView
                    {...this.props}
                    onRenderItem={(data) => {
                        this.state.views.push(
                            this._refreshItem(data.nativeEvent.key, data.nativeEvent.key)
                        );
                        this.setState({views: this.state.views});
                    }}
                    onRefresh={(data) => {
                        //加了会刷新不及时
                        // if (this.state.viewKeys[data.nativeEvent.key] == data.nativeEvent.index) {
                        //     return;
                        // }
                        // if (this.props.refresh) {
                        //     this.props.refresh(data.nativeEvent.index);
                        // }
                        this.state.views.splice(data.nativeEvent.key,1,this._refreshItem(data.nativeEvent.key, data.nativeEvent.index));
                        this.setState({views: this.state.views});// TODO 这里可以改成 UIManager.updateView 吗？
                    }}>
                    {this.state.views}
                </AndroidListView>
            </AndroidFrameLayout>
        );
    }

    _refreshItem = (key, index) => {
        let view = this.props.renderItem(key, this.props.data[index]);
        if(this.props.dividerHeight>0){
            //todo 设置paddingRight 后 想办法将其加到item上,或在java 层搞定这个事情
        }
        return view;
    }
}
